//
//  MyInformationViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/29.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "MyInformationViewController.h"
#import "EditPassWordViewController.h"
#import "EditInformationViewController.h"
#import "EditCompanyAddressViewController.h"
#import "purchaseButton.h"
#import "MyInformation.h"
#import "XlineView.h"
#import "EditHUDView.h"
@interface MyInformationViewController ()<UIScrollViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIAlertViewDelegate>{
    NSTimer *timer_;
}
@property (nonatomic,strong) UIScrollView *mainScroll;
@property (nonatomic,strong) NSMutableArray *memberArray;
@property (nonatomic,strong) NSMutableArray *companyArray;
@property (nonatomic,strong) NSString *province;
@property (nonatomic,strong) NSString *city;
@property (nonatomic,strong) NSString *address;
@property (nonatomic,strong) UIAlertView *successAlert;
@end

@implementation MyInformationViewController
@synthesize dataArray,titleArray,successAlert;
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.memberArray removeAllObjects];
    [self.companyArray removeAllObjects];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        TIME
        HEADDIC(nowTime, PROFILE);
        NSMutableDictionary *body = [NSMutableDictionary dictionary];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:HEAD forKey:@"head"];
        [dic setObject:body forKey:@"body"];
        requestManage *request = [[requestManage alloc]init];
        NSString *result = [Unity requestSomeApiData:HEAD withBody:body];
        NSLog(@"result___%@",result);
        dispatch_async(dispatch_get_main_queue(), ^{
            MyInformation *information = [[MyInformation alloc]init];
            [information parseResponseData:result];
            memberModel *member = [information.data objectForKey:@"member"];
            if (![Unity isBlankString:member.nickname]) {
                [self.memberArray addObject:member.nickname];
            }else{
                member.nickname = @"";
                [self.memberArray addObject:member.nickname];
            }
            if (![Unity isBlankString:member.qq]) {
                [self.memberArray addObject:member.qq];
            }else{
                member.qq = @"";
                [self.memberArray addObject:member.qq];
            }
            if (![Unity isBlankString:member.email]) {
                [self.memberArray addObject:member.email];
            }else{
                member.email = @"";
                [self.memberArray addObject:member.email];
            }
            if (![Unity isBlankString:member.mobile]) {
                [self.memberArray addObject:member.mobile];
            }else{
                member.mobile = @"";
                [self.memberArray addObject:member.mobile];
            }
            
            companyModel *company = [information.data objectForKey:@"company"];
            if (![Unity isBlankString:company]) {
                if (![Unity isBlankString:company.company_name]) {
                    [self.companyArray addObject:company.company_name];
                }else{
                    company.company_name = @"";
                    [self.companyArray addObject:company.company_name];
                }
                self.province = company.province;
                self.city = company.city;
                self.address = company.address;
                NSString *address = @"";
                if (![Unity isBlankString:company.province]) {
                    for (int i = 0; i < [[appStatus shareAppStatus].provinceArray count]; i++) {
                        NSMutableDictionary *dic = [[appStatus shareAppStatus].provinceArray objectAtIndex:i];
                        if ([[dic objectForKey:@"id"] isEqualToString:company.province]) {
                            address = [address stringByAppendingString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"city"]]];
                        }
                    }
                    for (int i = 0; i < [[appStatus shareAppStatus].cityArray count]; i++) {
                        NSMutableDictionary *dic = [[appStatus shareAppStatus].cityArray objectAtIndex:i];
                        if ([[dic objectForKey:@"id"] isEqualToString:company.city]) {
                            address = [address stringByAppendingString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"city"]]];
                        }
                    }
                }
                if (![Unity isBlankString:company.address]) {
                    address = [address stringByAppendingString:company.address];
                }
                [self.companyArray addObject:address];
                if (![Unity isBlankString:company.business]) {
                    [self.companyArray addObject:company.business];
                }else{
                    company.business = @"";
                    [self.companyArray addObject:company.business];
                }
                NSString *tel = nil;
                if (![Unity isBlankString:company.tel_pre]) {
                    tel = company.tel_pre;
                    if (![Unity isBlankString:company.tel]) {
                        tel = [NSString stringWithFormat:@"%@-%@",company.tel_pre,company.tel];
                    }
                }else{
                    if (![Unity isBlankString:company.tel]) {
                        tel = [NSString stringWithFormat:@"%@",company.tel];
                    }else{
                        tel = @"";
                    }
                }
                [self.companyArray addObject:tel];
            }
            [self superMainVC];
        });
    });
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    TABHIDDEN
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view setBackgroundColor:UIColorFromRGB(0xf2f2f2)];
    self.title = @"个人资料";
    self.memberArray = [NSMutableArray array];
    self.companyArray = [NSMutableArray array];
    // Do any additional setup after loading the view.
}
-(void)superMainVC{
    if (self.mainScroll) {
        [self.mainScroll removeFromSuperview];
        self.mainScroll = nil;
    }
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.frame = CGRectMake(0, 64, SWIDTH, VHEIGHT); // frame中的size指UIScrollView的可视范围
    scrollView.delegate = self;
    scrollView.tag = 255;
    scrollView.backgroundColor = [UIColor clearColor];
    self.mainScroll = scrollView;
    [self.view addSubview:scrollView];
    NSMutableArray *dataArray1 = [[NSMutableArray alloc] initWithObjects:@"姓名", @"QQ", @"邮箱",@"手机号码", nil];
    NSMutableArray *dataArray2 = [[NSMutableArray alloc] initWithObjects:@"公司名称", @"公司地址", @"经营模式",@"公司电话", nil];

    UIView *headView1 = [self createViewFrame:CGRectMake(0, 0, SWIDTH, 35) bgColor:UIColorFromRGB(0xf2f2f2) tag:0];
    [self.mainScroll addSubview:headView1];
    UILabel *lab1 = [self createLabelFrame:CGRectMake(10, 5, SWIDTH - 20, 30) title:@"个人信息" titleColor:UIColorFromRGB(0x666666) tag:0];
    lab1.font = [UIFont systemFontOfSize:13];
    [headView1 addSubview:lab1];
    int height = 0;
    for (int i = 0; i <[dataArray1 count]; i++) {
        purchaseButton *pButton = [[purchaseButton alloc]initWithFrame:CGRectMake(0, 35+40*i, SWIDTH, 40)];
        pButton.tag = 10+i;
        pButton.tempLab.text = [dataArray1 objectAtIndex:i];
//        [pButton setTitle:[self.memberArray objectAtIndex:i] forState:0];
        [pButton setTitleColor:GRAYColor forState:0];
        [pButton setBackgroundColor:[UIColor whiteColor]];
        pButton.titleLab.text = [self.memberArray objectAtIndex:i];
        [pButton addTarget:self action:@selector(informationClick:) forControlEvents:UIControlEventTouchUpInside];
        height = pButton.frame.origin.y + pButton.frame.size.height;
        XlineView *lineView = [[XlineView alloc]initWithFrame:CGRectMake(10, 39.5, SWIDTH - 20, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        lineView.alpha = 0.2;
        [pButton addSubview:lineView];
        [self.mainScroll addSubview:pButton];
    }
    UIView *headView2 = [self createViewFrame:CGRectMake(0, height, SWIDTH, 35) bgColor:UIColorFromRGB(0xf2f2f2) tag:0];
    [self.mainScroll addSubview:headView2];
    UILabel *lab2 = [self createLabelFrame:CGRectMake(10, 5, SWIDTH - 20, 30) title:@"公司信息" titleColor:UIColorFromRGB(0x666666) tag:0];
    lab2.font = [UIFont systemFontOfSize:13];
    [headView2 addSubview:lab2];
    int height1 = 0;
    for (int i = 0; i < [dataArray2 count]; i++) {
        purchaseButton *pButton = [[purchaseButton alloc]initWithFrame:CGRectMake(0, headView2.frame.size.height+headView2.frame.origin.y+40*i, SWIDTH, 40)];
        pButton.tag = 100+i;
        pButton.tempLab.text = [dataArray2 objectAtIndex:i];
        [pButton setBackgroundColor:[UIColor whiteColor]];
        [pButton setTitleColor:GRAYColor forState:0];
//        pButton.titleLab.text = [self.companyArray objectAtIndex:i];
        if ([self.companyArray count]!=0) {
//            [pButton setTitle:[self.companyArray objectAtIndex:i] forState:0];
            pButton.titleLab.text = [self.companyArray objectAtIndex:i];
        }else{
//            [pButton setTitle:@"" forState:0];
            pButton.titleLab.text = @"";
        }
        if ([pButton.tempLab.text isEqualToString:@"经营模式"]) {
            [pButton addTarget:self action:@selector(businessClick:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [pButton addTarget:self action:@selector(companyClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        height = pButton.frame.origin.y + pButton.frame.size.height;
        [self.mainScroll addSubview:pButton];
        height1 = pButton.frame.origin.y + pButton.frame.size.height;
        XlineView *lineView = [[XlineView alloc]initWithFrame:CGRectMake(10, 39.5, SWIDTH - 20, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        lineView.alpha = 0.2;
        [pButton addSubview:lineView];
    }
    purchaseButton *pButton = [[purchaseButton alloc]initWithFrame:CGRectMake(0, height1+10, SWIDTH, 40)];
    pButton.tag = 200;
    pButton.tempLab.text = @"修改密码";
    [pButton setBackgroundColor:[UIColor whiteColor]];
    [pButton setTitleColor:GRAYColor forState:0];
    pButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [pButton addTarget:self action:@selector(editPwd:) forControlEvents:UIControlEventTouchUpInside];
    height = pButton.frame.origin.y + pButton.frame.size.height;
    [self.mainScroll addSubview:pButton];
    [self.mainScroll setContentSize:CGSizeMake(SWIDTH, height1+50)];
    
}
-(void)businessClick:(purchaseButton *)sender{
    [self returnPickerView];
}
-(void)informationClick:(purchaseButton *)sender{
    purchaseButton *button = (purchaseButton *)sender;
    if ([sender.tempLab.text isEqualToString:@"手机号码"]) {
        SHOW_TITLEALERT(@"有材网提示", @"需要修改手机号码请登录有材网PC官网www.17youcai.com进行操作");
    }else {
        EditInformationViewController *information = [[EditInformationViewController alloc]init];
        information.title = [NSString stringWithFormat:@"修改%@",button.tempLab.text];
        information.viewInformation = button.titleLab.text;
        [self.navigationController pushViewController:information animated:YES];
    }
}
-(void)companyClick:(purchaseButton *)sender{
    purchaseButton *button = (purchaseButton *)sender;
    if ([button.tempLab.text isEqualToString:@"公司地址"]) {
        EditCompanyAddressViewController *addressVC = [[EditCompanyAddressViewController alloc]init];
        addressVC.title = @"修改公司地址";
        if (![Unity isBlankString:self.province]) {
            addressVC.province = self.province;
            addressVC.city = self.city;
            addressVC.address = self.address;
        }
        [self.navigationController pushViewController:addressVC animated:YES];
    }else{
        EditInformationViewController *information = [[EditInformationViewController alloc]init];
        information.title = [NSString stringWithFormat:@"修改%@",button.tempLab.text];
        information.viewInformation = button.titleLab.text;
        [self.navigationController pushViewController:information animated:YES];
    }
}
-(void)editPwd:(purchaseButton *)sender{
    EditPassWordViewController *pwdVC = [[EditPassWordViewController alloc]init];
    pwdVC.title = @"修改密码";
    [self.navigationController pushViewController:pwdVC animated:YES];
}
-(void)returnPickerView{
    UIView *tempView1 = (UIView *)[self.view viewWithTag:220];
    UIPickerView *pickV = (UIPickerView *)[tempView1 viewWithTag:221];
    if (pickV) {
        [pickV removeFromSuperview];
        pickV = nil;
    }
    UIToolbar *toolbar = (UIToolbar *)[tempView1 viewWithTag:223];
    if (toolbar) {
        [toolbar removeFromSuperview];
        toolbar = nil;
    }
    if (tempView1) {
        [tempView1 removeFromSuperview];
        tempView1 = nil;
    }
    UIView *tempView = (UIView *)[self createViewFrame:CGRectMake(0, SHEIGHT - 260, SWIDTH, 260) bgColor:[UIColor whiteColor] tag:220];
    [self.view addSubview:tempView];
    
    //创建工具栏
    NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:3];
    UIBarButtonItem *confirmBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(confirmPickView)];
    UIBarButtonItem *flexibleSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(pickerHide)];
    [items addObject:cancelBtn];
    [items addObject:flexibleSpaceItem];
    [items addObject:confirmBtn];
    
    UIPickerView *tempPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, SWIDTH, 216)];
    tempPicker.tag = 221;
    tempPicker.delegate = self;
    tempPicker.dataSource = self;
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, 44)];
    toolBar.tag = 223;
    toolBar.hidden = NO;
    toolBar.barStyle = UIBarStyleDefault;
    toolBar.items = items;
    [tempView addSubview:toolBar];
    [tempView addSubview:tempPicker];
}
-(void)confirmPickView{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        UIView *tempView = (UIView *)[self.view viewWithTag:220];
        UIPickerView *pickV = (UIPickerView *)[tempView viewWithTag:221];
        int select = [pickV selectedRowInComponent:0];
        purchaseButton *button = (purchaseButton *)[self.mainScroll viewWithTag:102];
        TIME
        HEADDIC(nowTime, SETCOMPANY);
        NSMutableDictionary *body = [NSMutableDictionary dictionary];
        [body setObject:[[appStatus shareAppStatus].business objectAtIndex:select] forKey:@"business"];
        NSString *result = [Unity requestSomeApiData:HEAD withBody:body];
        NSMutableDictionary *json = [result objectFromJSONString];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([[json objectForKey:@"err_code"] integerValue]==0) {
                button.titleLab.text = [[appStatus shareAppStatus].business objectAtIndex:select];
                if (tempView) {
                    [tempView removeFromSuperview];
//                    tempView = nil;
                }
                EditHUDView *hudView = [[EditHUDView alloc]initWithFrame:CGRectMake(0, 64, SWIDTH, VHEIGHT)];
                hudView.backgroundColor = [UIColor clearColor];
                hudView.tag = 1010;
                hudView.alertLab.text = [json objectForKey:@"err_message"];
                [self.view addSubview:hudView];
                timer_ = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(doTime) userInfo:nil repeats:NO];
            }else{
                SHOW_ALERT([json objectForKey:@"err_message"]);
            }
        });
    });

    
    
}
-(void)doTime
{
    //alert过1秒自动消失
    [self resetTimer];
    [self removeHudView];
}
-(void)removeHudView{
    EditHUDView *hudView = (EditHUDView *)[self.view viewWithTag:1010];
    if (hudView) {
        [hudView removeFromSuperview];
        hudView = nil;
    }
}
-(void) resetTimer
{
    if (timer_) {
        [timer_ invalidate];
        timer_ = nil;
    }
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    NSLog(@"alert");
    [self.successAlert removeFromSuperview];
    self.successAlert = nil;
}

-(void)pickerHide{
    [self removePickerView];
}

-(void)removePickerView{
    UIView *tempView = (UIView *)[self.view viewWithTag:220];
    if (tempView) {
        [tempView removeFromSuperview];
        tempView = nil;
    }
}

#pragma mark --
#pragma mark--UIPickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [[appStatus shareAppStatus].business count];
}
#pragma mark--
#pragma mark--UIPickerViewDelegate
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [[appStatus shareAppStatus].business objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"row is %ld,Component is %ld",row,component);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
